package cn.ubeta.b2c.update;

import android.app.Activity;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;

import cn.ubeta.b2c.widget.DownLoadProgressDialog;

/**
 * Created by denny on 16/6/29.
 */

public class UpdateHelper {

    /**
     * 检查新版本
     */
    public static void checkUpdate(final Activity activity) {
        /*
        ApiItem item = new ApiItem(activity, "/activity/appUpdate", true);
        NetworkHelper.callAPIEx(item, new ResultCallback<UpdateInfo>() {
            @Override
            public void onResponse(UpdateInfo updateInfo) {
                //updateInfo.setUpStatus(2);
                //updateInfo.setVersion("2.0.3");
                int status = updateInfo.getUpStatus();
                if (status > 0 && compareVersion(updateInfo.getVersion(), BuildConfig.VERSION_NAME)) {
                    showUpdateDialog(activity, status == 2, updateInfo.getVersion(), updateInfo.getPromptWord(), updateInfo.getUpContent(), updateInfo.getApkUrl());
                }
            }
        });
        */
    }

    /**
     * 弹出升级提示对话框
     *
     * @param forceUpdate
     * @param title
     * @param content
     */
    private static void showUpdateDialog(final Activity activity, final boolean forceUpdate, final String version, String title, String content, final String apkUrl) {
        AlertDialog.Builder dialog = new AlertDialog.Builder(activity);
        // 点击对话框区域外不关闭
        dialog.setCancelable(false);
        dialog.setTitle(title);
        dialog.setMessage(content);
        dialog.setNegativeButton(forceUpdate ? "退出" : "取消", (dialogInterface, i) -> {
            if (forceUpdate) {
                activity.finish();
            }
        });
        dialog.setPositiveButton("立即更新", (dialogInterface, i) -> {
            // 下载不可取消
            new DownLoadProgressDialog(activity, "正在下载...", version, apkUrl, false, false).show();
        });
        dialog.show();
    }

    /**
     * 比较版本号的大小,前者大则返回一个正数,后者大返回一个负数,相等则返回0
     *
     * @param newVersion
     * @param current
     * @return
     */
    private static boolean compareVersion(String newVersion, String current) {
        if (TextUtils.isEmpty(newVersion) || TextUtils.isEmpty(current)) {
            return false;
        }
        String[] newVerArray = newVersion.split("\\."); // 注意此处为正则匹配，不能用"."
        String[] curVerArray = current.split("\\.");
        int idx = 0;
        int minLength = Math.min(newVerArray.length, curVerArray.length); // 取最小长度值
        int diff = 0;
        while (idx < minLength
                && (diff = newVerArray[idx].length() - curVerArray[idx].length()) == 0 // 先比较长度
                && (diff = newVerArray[idx].compareTo(curVerArray[idx])) == 0) { // 再比较字符
            ++idx;
        }
        // 如果已经分出大小，则直接返回，如果未分出大小，则再比较位数，有子版本的为大
        diff = (diff != 0) ? diff : newVerArray.length - curVerArray.length;
        return diff > 0;
    }
}